package players;

import bin.Mud;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class ImportPlayerFile {
    File file = new File("C:\\Dev\\FBMud\\src\\main\\java\\players\\me.txt");
    private Mud mudWindow;

    public ImportPlayerFile(Mud mudWindow) {
        this.mudWindow = mudWindow;
    }

    public String getFile() {
        String s;
        StringBuilder build = new StringBuilder();


        try {
            FileInputStream fstream = new FileInputStream(file);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            while ((s = br.readLine()) != null) {
                if (!s.startsWith("ImageURL=")) {
                    build.append(s);
                    build.append("\n");
                }
            }

        } catch (Exception e) {
            mudWindow.setReturnText(e.getMessage());
        }
        return build.toString();
    }

    public String getURL() {
        String s;
        String url = "no URL";

        try {
            FileInputStream fstream = new FileInputStream(file);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            while ((s = br.readLine()) != null) {
                if (s.startsWith("ImageURL=")) {
                    url = s.replaceFirst("ImageURL=", "");
                }
            }

        } catch (Exception e) {
            mudWindow.setReturnText(e.getMessage());
        }
        return url;
    }

    public void getImage() {
        try {
            URL web = new URL(getURL());
            URLConnection yc = web.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                mudWindow.setTextImage(inputLine);
                mudWindow.setTextImage("\n");
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}